#include "FTPClient.h"
#include <curl/curl.h>
#include <QMessageBox>
#include <QDir>
#include <QFile>

#include <QFileInfoList>
#include <QDateTime>
#include <QTemporaryFile>
#include <sstream>


FTPClient::FTPClient(QWidget *parent)
    : QWidget(parent)
{
	

    ui.setupUi(this);

	
	ui.ld_ip->setText("192.168.33.249");
	ui.ld_port->setText("21");
	ui.ld_userName->setText("Administrator");
	ui.ld_passWord->setText("917");

	//ui.ld_downLoadPath->setText("D:\\FtpSharedFloder\\down");
	/*ui.ld_pushPath->setText("D:\\FtpSharedFloder\\push");*/
	ui.ld_downLoadPath->setText("down");
	ui.ld_pushPath->setText("push");
	
	ui.ld_localSavePath->setText("C:\\Users\\Administrator\\Desktop\\FTPClient\\DownLoad");

	m_ip = ui.ld_ip->text();
	m_port = ui.ld_port->text();
	m_username = ui.ld_userName->text();
	m_password = ui.ld_passWord->text();

	m_downLoadPath= ui.ld_downLoadPath->text();
	m_pushPath = ui.ld_pushPath->text();
	m_localSavePath = ui.ld_localSavePath->text();
}


void FTPClient::on_btn_connect_clicked()
{
	CURL *curl;
	CURLcode res;
	curl_global_init(CURL_GLOBAL_DEFAULT);
	curl = curl_easy_init();

	if (curl) {
		QString url = QString("ftp://%1:%2").arg(m_ip).arg(m_port);
		curl_easy_setopt(curl, CURLOPT_URL, url.toStdString().c_str());
		curl_easy_setopt(curl, CURLOPT_USERNAME, m_username.toStdString().c_str());
		curl_easy_setopt(curl, CURLOPT_PASSWORD, m_password.toStdString().c_str());

		// Perform the request, res will get the return code
		res = curl_easy_perform(curl);

		// Check for errors
		if (res != CURLE_OK) {
			QMessageBox::critical(this, "Connection Status", "Failed to connect to FTP server: " + QString(curl_easy_strerror(res)));
		}
		else {
			QMessageBox::information(this, "Connection Status", "Connected to FTP server successfully.");
		}

		// Always cleanup
		curl_easy_cleanup(curl);
	}

	curl_global_cleanup();
}


size_t ListCallback(void *ptr, size_t size, size_t nmemb, void *stream)
{
	std::string data((const char*)ptr, (size_t)size * nmemb);
	std::stringstream *response = static_cast<std::stringstream*>(stream);
	response->write(data.c_str(), (std::streamsize)data.size());
	return size * nmemb;
}

QStringList getFTPFileList(const QString& url, const QString& username, const QString& password)
{
	CURL *curl;
	CURLcode res;
	std::stringstream response;

	curl_global_init(CURL_GLOBAL_DEFAULT);
	curl = curl_easy_init();

	if (curl)
	{
		curl_easy_setopt(curl, CURLOPT_URL, url.toStdString().c_str());
		curl_easy_setopt(curl, CURLOPT_USERNAME, username.toStdString().c_str());
		curl_easy_setopt(curl, CURLOPT_PASSWORD, password.toStdString().c_str());
		curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, ListCallback);
		curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response);
		curl_easy_setopt(curl, CURLOPT_DIRLISTONLY, 1L);

		res = curl_easy_perform(curl);

		if (res != CURLE_OK)
		{
			qDebug() << "curl_easy_perform() failed: " << curl_easy_strerror(res);
		}

		curl_easy_cleanup(curl);
	}

	curl_global_cleanup();

	QStringList fileList;
	QString data = QString::fromStdString(response.str());
	QStringList lines = data.split("\n");

	foreach(QString line, lines)
	{
		line = line.trimmed();
		if (!line.isEmpty() && line.endsWith(".txt"))
		{
			fileList << line;
		}
	}

	return fileList;
}

size_t WriteCallback(void *ptr, size_t size, size_t nmemb, FILE *stream)
{
	return fwrite(ptr, size, nmemb, stream);
}

//void FTPClient::on_btn_downLoad_clicked()
//{
//	QString ftpUrl = QString("ftp://%1/%2/").arg(m_ip, m_downLoadPath);
//	QStringList fileNames = getFTPFileList(ftpUrl, m_username, m_password);
//
//	if (fileNames.isEmpty())
//	{
//		QMessageBox::information(this, "信息", "在FTP服务器上没有找到任何txt文件。");
//		return;
//	}
//
//	if (ui.ck_save->isChecked())
//	{
//		//将FTP服务端中m_downLoadPath路径下的后缀为txt的文件全部复制到本地的文件夹m_localSavePath中
//		foreach(const QString& fileName, fileNames)
//		{
//			QString sourceFilePath = QString("ftp://%1/%2/%3").arg(m_ip, m_downLoadPath, fileName);
//			QString destinationFilePath = m_localSavePath + "/" + fileName;
//
//			// 使用libcurl下载文件
//			CURL *curl;
//			FILE *fp;
//			CURLcode res;
//
//			curl_global_init(CURL_GLOBAL_DEFAULT);
//			curl = curl_easy_init();
//			if (curl)
//			{
//				fp = fopen(destinationFilePath.toStdString().c_str(), "wb");
//				if (fp)
//				{
//					curl_easy_setopt(curl, CURLOPT_URL, sourceFilePath.toStdString().c_str());
//					curl_easy_setopt(curl, CURLOPT_USERNAME, m_username.toStdString().c_str());
//					curl_easy_setopt(curl, CURLOPT_PASSWORD, m_password.toStdString().c_str());
//					curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
//					curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
//
//					res = curl_easy_perform(curl);
//					if (res != CURLE_OK)
//					{
//						QMessageBox::critical(this, "FTP下载错误", "无法下载文件 " + fileName + ": " + QString(curl_easy_strerror(res)));
//					}
//					else
//					{
//						QMessageBox::information(this, "FTP下载状态", "文件 " + fileName + " 成功下载到本地。");
//					}
//
//					fclose(fp);
//				}
//				curl_easy_cleanup(curl);
//			}
//			curl_global_cleanup();
//		}
//	}
//	else
//	{
//		//将FTP服务端中m_downLoadPath路径下的后缀为txt的文件全部复制到服务端的文件夹m_pushPath中
//		foreach(const QString& fileName, fileNames)
//		{
//			QString sourceFilePath = QString("ftp://%1/%2/%3").arg(m_ip, m_downLoadPath, fileName);
//			QString destinationFilePath = QString("ftp://%1/%2/%3").arg(m_ip, m_pushPath, fileName);
//
//			// 使用libcurl复制文件
//			CURL *curl;
//			CURLcode res;
//			QTemporaryFile tempFile;
//
//			if (tempFile.open())
//			{
//				QString tempFileName = tempFile.fileName();
//
//				// 下载文件到临时文件
//				curl_global_init(CURL_GLOBAL_DEFAULT);
//				curl = curl_easy_init();
//				if (curl)
//				{
//					FILE *fp = fopen(tempFileName.toStdString().c_str(), "wb");
//					if (fp)
//					{
//						curl_easy_setopt(curl, CURLOPT_URL, sourceFilePath.toStdString().c_str());
//						curl_easy_setopt(curl, CURLOPT_USERNAME, m_username.toStdString().c_str());
//						curl_easy_setopt(curl, CURLOPT_PASSWORD, m_password.toStdString().c_str());
//						curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
//						curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
//
//						res = curl_easy_perform(curl);
//						fclose(fp);
//
//						if (res != CURLE_OK)
//						{
//							QMessageBox::critical(this, "FTP下载错误", "无法下载文件 " + fileName + ": " + QString(curl_easy_strerror(res)));
//							curl_easy_cleanup(curl);
//							continue;
//						}
//					}
//					curl_easy_cleanup(curl);
//				}
//
//				// 上传临时文件到目标路径
//				curl = curl_easy_init();
//				if (curl)
//				{
//					FILE *fp = fopen(tempFileName.toStdString().c_str(), "rb");
//					if (fp)
//					{
//						fseek(fp, 0, SEEK_END);
//						long fileSize = ftell(fp);
//						fseek(fp, 0, SEEK_SET);
//
//						curl_easy_setopt(curl, CURLOPT_URL, destinationFilePath.toStdString().c_str());
//						curl_easy_setopt(curl, CURLOPT_USERNAME, m_username.toStdString().c_str());
//						curl_easy_setopt(curl, CURLOPT_PASSWORD, m_password.toStdString().c_str());
//						curl_easy_setopt(curl, CURLOPT_UPLOAD, 1L);
//						curl_easy_setopt(curl, CURLOPT_READDATA, fp);
//						curl_easy_setopt(curl, CURLOPT_INFILESIZE_LARGE, (curl_off_t)fileSize);
//
//						res = curl_easy_perform(curl);
//						fclose(fp);
//
//						if (res != CURLE_OK)
//						{
//							QMessageBox::critical(this, "FTP上传错误", "无法上传文件 " + fileName + " 到目标路径: " + QString(curl_easy_strerror(res)));
//						}
//						else
//						{
//							QMessageBox::information(this, "FTP上传状态", "文件 " + fileName + " 成功复制到目标路径。");
//						}
//					}
//					curl_easy_cleanup(curl);
//				}
//				curl_global_cleanup();
//			}
//		}
//	}
//}




void FTPClient::on_btn_downLoad_clicked()
{
	QString ftpUrl = QString("ftp://%1/%2/").arg(m_ip, m_downLoadPath);
	QStringList fileNames = getFTPFileList(ftpUrl, m_username, m_password);

	if (fileNames.isEmpty())
	{
		QMessageBox::information(this, "信息", "在FTP服务器上没有找到任何txt文件。");
		return;
	}

	QString timestamp = QDateTime::currentDateTime().toString("yyyy-MM-dd-HH-mm-ss");

	if (ui.ck_save->isChecked())
	{
		// 将FTP服务端中m_downLoadPath路径下的后缀为txt的文件全部复制到本地的文件夹m_localSavePath中
		foreach(const QString& fileName, fileNames)
		{
			QString sourceFilePath = QString("ftp://%1/%2/%3").arg(m_ip, m_downLoadPath, fileName);
			QString baseName = QFileInfo(fileName).baseName();
			QString extension = QFileInfo(fileName).suffix();
			QString newFileName = QString("%1_%2.%3").arg(baseName, timestamp, extension);
			QString destinationFilePath = m_localSavePath + "/" + newFileName;

			// 使用libcurl下载文件
			CURL *curl;
			FILE *fp;
			CURLcode res;

			curl_global_init(CURL_GLOBAL_DEFAULT);
			curl = curl_easy_init();
			if (curl)
			{
				fp = fopen(destinationFilePath.toStdString().c_str(), "wb");
				if (fp)
				{
					curl_easy_setopt(curl, CURLOPT_URL, sourceFilePath.toStdString().c_str());
					curl_easy_setopt(curl, CURLOPT_USERNAME, m_username.toStdString().c_str());
					curl_easy_setopt(curl, CURLOPT_PASSWORD, m_password.toStdString().c_str());
					curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
					curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);

					res = curl_easy_perform(curl);
					if (res != CURLE_OK)
					{
						QMessageBox::critical(this, "FTP下载错误", "无法下载文件 " + fileName + ": " + QString(curl_easy_strerror(res)));
					}
					else
					{
						QMessageBox::information(this, "FTP下载状态", "文件 " + fileName + " 成功下载到本地 " + newFileName + "。");
					}

					fclose(fp);
				}
				curl_easy_cleanup(curl);
			}
			curl_global_cleanup();
		}
	}
	else
	{
		// 将FTP服务端中m_downLoadPath路径下的后缀为txt的文件全部复制到服务端的文件夹m_pushPath中
		foreach(const QString& fileName, fileNames)
		{
			QString sourceFilePath = QString("ftp://%1/%2/%3").arg(m_ip, m_downLoadPath, fileName);
			QString baseName = QFileInfo(fileName).baseName();
			QString extension = QFileInfo(fileName).suffix();
			QString newFileName = QString("%1_%2.%3").arg(baseName, timestamp, extension);
			QString destinationFilePath = QString("ftp://%1/%2/%3").arg(m_ip, m_pushPath, newFileName);

			// 使用libcurl复制文件
			CURL *curl;
			CURLcode res;
			QTemporaryFile tempFile;

			if (tempFile.open())
			{
				QString tempFileName = tempFile.fileName();

				// 下载文件到临时文件
				curl_global_init(CURL_GLOBAL_DEFAULT);
				curl = curl_easy_init();
				if (curl)
				{
					FILE *fp = fopen(tempFileName.toStdString().c_str(), "wb");
					if (fp)
					{
						curl_easy_setopt(curl, CURLOPT_URL, sourceFilePath.toStdString().c_str());
						curl_easy_setopt(curl, CURLOPT_USERNAME, m_username.toStdString().c_str());
						curl_easy_setopt(curl, CURLOPT_PASSWORD, m_password.toStdString().c_str());
						curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
						curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);

						res = curl_easy_perform(curl);
						fclose(fp);

						if (res != CURLE_OK)
						{
							QMessageBox::critical(this, "FTP下载错误", "无法下载文件 " + fileName + ": " + QString(curl_easy_strerror(res)));
							curl_easy_cleanup(curl);
							continue;
						}
					}
					curl_easy_cleanup(curl);
				}

				// 上传临时文件到目标路径
				curl = curl_easy_init();
				if (curl)
				{
					FILE *fp = fopen(tempFileName.toStdString().c_str(), "rb");
					if (fp)
					{
						fseek(fp, 0, SEEK_END);
						long fileSize = ftell(fp);
						fseek(fp, 0, SEEK_SET);

						curl_easy_setopt(curl, CURLOPT_URL, destinationFilePath.toStdString().c_str());
						curl_easy_setopt(curl, CURLOPT_USERNAME, m_username.toStdString().c_str());
						curl_easy_setopt(curl, CURLOPT_PASSWORD, m_password.toStdString().c_str());
						curl_easy_setopt(curl, CURLOPT_UPLOAD, 1L);
						curl_easy_setopt(curl, CURLOPT_READDATA, fp);
						curl_easy_setopt(curl, CURLOPT_INFILESIZE_LARGE, (curl_off_t)fileSize);

						res = curl_easy_perform(curl);
						fclose(fp);

						if (res != CURLE_OK)
						{
							QMessageBox::critical(this, "FTP上传错误", "无法上传文件 " + newFileName + " 到目标路径: " + QString(curl_easy_strerror(res)));
						}
						else
						{
							QMessageBox::information(this, "FTP上传状态", "文件 " + fileName + " 成功复制到目标路径 " + newFileName + "。");
						}
					}
					curl_easy_cleanup(curl);
				}
				curl_global_cleanup();
			}
		}
	}
}





